<template>
  <Layout>
    <div class="advertisement-container">
      <!-- 功能入口区域 -->
      <div class="function-area">
        <el-button type="primary" @click="handleCreateAd">新建广告</el-button>
        <div class="search-area">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item>
              <el-input
                v-model="searchForm.name"
                placeholder="请输入广告名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchForm.status" placeholder="全部" clearable>
                <el-option label="全部" value="" />
                <el-option label="待上线" :value="0" />
                <el-option label="上线中" :value="1" />
                <el-option label="已下线" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 数据列表 -->
      <div class="data-table">
        <el-table
          :data="adList"
          style="width: 100%"
          v-loading="loading"
          border
        >
          <el-table-column prop="name" label="广告名称" min-width="150" />
          <el-table-column prop="position" label="位置" min-width="180" />
          <el-table-column prop="sort" label="权重" width="80" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" min-width="180">
            <template #default="scope">
              {{ formatTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleViewData(scope.row)"
              >
                数据
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.status === 1"
                link
                type="warning"
                size="small"
                @click="handleChangeStatus(scope.row, 2)"
              >
                下线
              </el-button>
              <el-button
                v-if="scope.row.status === 0 || scope.row.status === 2"
                link
                type="success"
                size="small"
                @click="handleChangeStatus(scope.row, 1)"
              >
                上线
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="adList.length === 0 && !loading" description="暂无数据" />
    </div>

    <!-- 广告详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑广告' : '新增广告'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="adForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="adForm.name" placeholder="请输入广告名称" maxlength="40" show-word-limit />
        </el-form-item>
        <el-form-item label="广告位置" prop="position">
          <el-input v-model="adForm.position" placeholder="请输入广告位置" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            class="ad-uploader"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            v-model:file-list="fileList"
            :on-change="handleFileChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800*450像素，仅支持JPG/PNG格式</div>
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="adForm.link" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="权重" prop="sort">
          <el-input-number v-model="adForm.sort" :min="0" :max="99" />
          <div class="sort-tip">数值越大越靠前</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="adForm.status">
            <el-radio :label="0">待上线</el-radio>
            <el-radio :label="1">上线中</el-radio>
            <el-radio :label="2">已下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { 
  getAdvertisementList, 
  createAdvertisement, 
  updateAdvertisement, 
  deleteAdvertisement,
  updateAdvertisementStatus
} from '@/api/advertisement';
import { cosUtil } from "@/utils/cos"; // 导入腾讯云COS工具类

// 加载状态
const loading = ref(false);

// 广告列表数据
const adList = ref<any[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();
const fileList = ref<any[]>([]);

// 广告表单
const adForm = reactive({
  objectId: '',
  name: '',
  position: '',
  image: '',
  link: '',
  sort: 0,
  status: 0,
  imageFile: null as File | null // 添加文件对象属性
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入广告名称', trigger: 'blur' },
    { max: 40, message: '广告名称不能超过40个字符', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入广告位置', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传广告图片', trigger: 'change' }
  ]
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待上线',
    1: '上线中',
    2: '已下线'
  };
  return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'danger'
  };
  return typeMap[status] || 'info';
};

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
};

// 加载广告列表
const loadAdList = async () => {
  loading.value = true;
  try {
    const params: any = {
      limit: pageSize.value,
      skip: (currentPage.value - 1) * pageSize.value
    };
    
    // 添加搜索条件
    if (searchForm.name) {
      // LeanCloud 支持正则查询，这里使用正则实现模糊搜索
      params.where = JSON.stringify({
        name: { $regex: `.*${searchForm.name}.*` }
      });
    }
    
    if (searchForm.status !== '') {
      const whereObj = params.where ? JSON.parse(params.where) : {};
      whereObj.status = Number(searchForm.status);
      params.where = JSON.stringify(whereObj);
    }
    
    const response: any = await getAdvertisementList(params);
    adList.value = response.results || [];
    total.value = response.count || 0;
  } catch (error) {
    console.error('获取广告列表失败:', error);
    ElMessage.error('获取广告列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadAdList();
};

// 处理重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.status = '';
  currentPage.value = 1;
  loadAdList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadAdList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadAdList();
};

// 处理新建广告
const handleCreateAd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  resetForm();
  
  // 填充表单数据
  adForm.objectId = row.objectId;
  adForm.name = row.name;
  adForm.position = row.position;
  adForm.image = row.image;
  adForm.link = row.link || '';
  adForm.sort = row.sort || 0;
  adForm.status = row.status;
  adForm.imageFile = null; // 清空文件对象，编辑时如果不上传新图片则使用原图片
  
  // 如果有图片，添加到文件列表
  if (row.image) {
    fileList.value = [
      {
        name: 'advertisement',
        url: row.image
      }
    ];
  } else {
    fileList.value = [];
  }
  
  dialogVisible.value = true;
};

// 处理查看数据
const handleViewData = (row: any) => {
  ElMessage.info('数据详情功能待开发');
};

// 处理状态变更
const handleChangeStatus = (row: any, newStatus: number) => {
  const statusText = newStatus === 1 ? '上线' : '下线';
  ElMessageBox.confirm(`是否确认${statusText}该广告？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateAdvertisementStatus(row.objectId, newStatus);
      ElMessage.success(`广告已${statusText}`);
      loadAdList();
    } catch (error) {
      console.error(`广告${statusText}失败:`, error);
      ElMessage.error(`广告${statusText}失败`);
    }
  }).catch(() => {});
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('是否确认删除该广告？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAdvertisement(row.objectId);
      ElMessage.success('广告已删除');
      loadAdList();
    } catch (error) {
      console.error('删除广告失败:', error);
      ElMessage.error('删除广告失败');
    }
  }).catch(() => {});
};

// 处理文件变更
const handleFileChange = (file: any) => {
  console.log("图片变更:", file);
  // 如果是新上传的图片，创建临时URL用于预览
  if (file && file.raw) {
    // 保存文件对象，提交表单时上传
    adForm.imageFile = file.raw;
    // 创建临时URL用于预览
    adForm.image = URL.createObjectURL(file.raw);
  }
};

// 重置表单
const resetForm = () => {
  adForm.objectId = '';
  adForm.name = '';
  adForm.position = '';
  adForm.image = '';
  adForm.link = '';
  adForm.sort = 0;
  adForm.status = 0;
  adForm.imageFile = null; // 清空文件对象
  fileList.value = [];
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 准备广告数据
        const data = {
          name: adForm.name,
          position: adForm.position,
          image: adForm.image, // 这个值会在上传成功后被替换
          link: adForm.link,
          sort: adForm.sort,
          status: adForm.status
        };
        
        // 处理图片上传
        if (adForm.imageFile) {
          try {
            // 上传图片到腾讯云COS
            console.log('开始上传图片到腾讯云COS');
            const imageUrl = await cosUtil.uploadFile(adForm.imageFile);
            console.log('图片上传成功:', imageUrl);
            // 更新图片URL
            data.image = imageUrl;
          } catch (error) {
            console.error('上传图片到腾讯云COS失败:', error);
            ElMessage.error('上传图片失败: ' + (error as Error).message);
            return;
          }
        } else if (!isEdit.value && !data.image) {
          // 如果是新增且没有上传图片，使用默认图片
          data.image = 'https://placehold.co/600x400';
        }
        
        // 保存广告数据
        if (isEdit.value) {
          await updateAdvertisement(adForm.objectId, data);
          ElMessage.success('编辑成功');
        } else {
          await createAdvertisement(data);
          ElMessage.success('新增成功');
        }
        
        dialogVisible.value = false;
        loadAdList();
      } catch (error) {
        console.error('保存广告失败:', error);
        ElMessage.error('保存广告失败: ' + (error as Error).message);
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadAdList();
});
</script>

<style scoped>
.advertisement-container {
  padding: 0;
}

.function-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.search-area {
  flex-grow: 1;
  display: flex;
  justify-content: flex-end;
}

.data-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ad-uploader {
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.sort-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  margin-left: 10px;
}
</style> 